﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Web;
using System.Text.RegularExpressions;

namespace LuKou.Web.Core
{
    public static class Public
    {
        /// <summary>
        /// 网站应用程序根目录
        /// </summary>
        public static string WebRootPath
        {
            get
            {
                return System.Web.HttpContext.Current.Request.PhysicalApplicationPath;
            }
        }

        /// <summary>
        /// 生成随机密码
        /// </summary>
        /// <param name="pwdlen">密码长度</param>
        /// <returns></returns>
        public static string MakePassword(int pwdlen)
        {
            byte[] bytes = new byte[pwdlen];
            string checkCode = "";

            RNGCryptoServiceProvider r = new RNGCryptoServiceProvider();
            r.GetBytes(bytes);

            foreach (byte number in bytes)
            {
                if (number % 2 == 0)
                    checkCode += ((char)('1' + (char)(number % 9))).ToString();
                else if (number % 3 == 0)
                    checkCode += ((char)('A' + (char)(number % 26))).ToString();
                else
                    checkCode += ((char)('a' + (char)(number % 26))).ToString();
            }
            return checkCode;
        }

        /// <summary>
        /// 生成随机数
        /// </summary>
        /// <param name="len">随机数长度</param>
        /// <returns></returns>
        public static string MakeRand(int len)
        {
            byte[] bytes = new byte[len];
            string checkCode = "";

            RNGCryptoServiceProvider r = new RNGCryptoServiceProvider();
            r.GetBytes(bytes);

            foreach (byte number in bytes)
            {
                checkCode += ((char)('1' + (char)(number % 9))).ToString();
            }
            return checkCode;
        }

        /// <summary>
        /// 获取用户IP
        /// </summary>
        /// <returns></returns>
        public static string UserIP
        {
            get
            {
                string input = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                if (String.IsNullOrEmpty(input))
                    input = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                if (!Regex.IsMatch(input, "^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$"))
                {
                    return "Unknown";
                }
                return input;
            }
        }
    }
}
